package com.xiaoma.mvi.func

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType
import kotlin.collections.set

abstract class BindingFragment<T : ViewBinding> : Fragment() {
    private var _binding: T? = null
    protected val binding: T get() = _binding!!

    companion object {
        private val viewBindingClassCache =
            mutableMapOf<Class<out Fragment>, Class<out ViewBinding>>()
    }

    final override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ) = onCreateViewBinding(
        inflater,
        container,
        savedInstanceState
    ).run { _binding = this; root }

    @Suppress("UNCHECKED_CAST")
    protected open fun onCreateViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ) = this::class.java.run {
        viewBindingClassCache[this] ?: run {
            val type = (genericSuperclass as ParameterizedType)
            val arguments = type.actualTypeArguments
            val viewBindingClass = arguments.first() as Class<T>
            viewBindingClassCache[this] = viewBindingClass
            viewBindingClass
        }
    }.getMethod(
        "inflate",
        LayoutInflater::class.java,
        ViewGroup::class.java,
        Boolean::class.java
    ).invoke(null, inflater, container, false) as T

    @CallSuper
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}